package irc.controller;

import irc.view.ConnectionView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;



/**
 * This class manage the connectionview and the actionlisteners for the connectpanel
 * @author Dybdal
 * @version 1.5
 * @since 1.1
 */

public class ConnectionController {
	private ConnectionView CView;
	private BaseController CC;
	private JFrame frame;
	MenuController menuC;
	ToolbarController toolbarC;


	
	/** Constructor: this creates the connection view and gets the basecontroller
	 * @author Dybdal
	 * @since 1.1
	 */
	public ConnectionController(BaseController CC){
		this.CC = CC;
		CView = new ConnectionView(this);
		frame = CView.getFrame();
	}


	/**
	 *  Actionlisteners for the connectpanel
	 *  @author Dybdal
	 * @since 1.2
	 * @version 1.3
	 */
	public void connectPanelActionListeners(JButton ok, JButton avbryt, JButton hjelp, JButton addServer, JButton edit, JButton delete, JButton sort){
		
		//--------------------------------------- ok button -----------------------------
		ok.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				for(String[] data : CView.getServers()){	// loops trough the servers
					String[] tmp = data[0].split("=");		// splits the name object
					tmp[1] = tmp[1].substring(0, tmp[1].length()-6);	// cuts SERVER from name
					if(tmp[1].equals(CView.getServer().getSelectedItem()) && data[3].equals(CView.getSelector().getSelectedItem())){	// if the name in the comboboxes matches whit the line
						String network = CView.getSelector().getSelectedItem().toString();	// converts the combobox item to string
						if(CC.connectToServer(CView.getNick(), data[1], network) == true){ // if connection complete
							menuC.hideConnect(); // hide the connect button in menu
							toolbarC.hideConnect();	// hide the connect button in toolbar
							CView.storeDefaultSettings();	// stores the data
						}
					}
				}
				frame.dispose();	// close the frame
			}
		});
		
		//--------------------------------------- avbryt button -----------------------------
		avbryt.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				frame.hide();	// hides the frame
			}
		});
		
		//--------------------------------------- help button -----------------------------
		hjelp.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				JOptionPane.showMessageDialog(frame, "Choose a server, then type in your name, e-mail and nick");
				// shows a help message
			}
		});
		
		//--------------------------------------- addserver button -----------------------------
		addServer.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				String[] input = serverConfig(null,null,null,null);	// starts a dialog to put in serverinfo
				if(input != null){	// if its not null
				CView.getServers().add(input);	// adds it to the serverlist
				CView.setServers(CView.getSelector().getSelectedIndex()); // refreshing the server combobox
				CView.getServer().updateUI(); // updates the combobox
				}
			}
		});
		
		//--------------------------------------- edit button -----------------------------
		edit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				ArrayList<String> srvInfo = findSelectedServer(); // finds the selected server in combobox
				String[] serverName = srvInfo.get(0).split("=");	// splits the name
				String serverNameSplited = serverName[1].substring(0, serverName[1].length()-6); // cuts SERVER from name
				String[] port = srvInfo.get(2).split("G"); // splits the network name
				String[] input = serverConfig(serverNameSplited, srvInfo.get(1), port[0],srvInfo.get(3)); // adds the data to the edit dialog
				if(input != null){ // if not null
				for(int i = 0; i < 4; i++)	{ // loops trough the returned array
					CView.getServers().get(Integer.parseInt(srvInfo.get(4)))[i] = input[i];
				}	// changing the vaules for the selected server
				CView.setServers(CView.getSelector().getSelectedIndex()); // refreshing the server combobox
				CView.getServer().updateUI(); // updates the combobox
				}
			}
		});
		
		//--------------------------------------- delete button -----------------------------
		delete.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				ArrayList<String> delete = findSelectedServer();	//finds the selected server
					//shows a dialog the says if you want to delete the server
				if(JOptionPane.showConfirmDialog(null,"Do you want to delete this server?","Delete server", JOptionPane.YES_NO_CANCEL_OPTION) == 0){
					CView.getServers().remove(Integer.parseInt(delete.get(4))); // removes the server from serverlist
					CView.setServers(CView.getSelector().getSelectedIndex());// refreshing the servercombobox
					CView.getServer().updateUI();	//updates the combobox
				}
				
			}
		});
		
		//--------------------------------------- sort button -----------------------------
		sort.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				ArrayList<String> list = new ArrayList<String>(); // creates a temp list to sort
				for(int i = 0; i < CView.getServers().size(); i++){		 //loops trough the serverlist				
					if(CView.getServers().get(i)[3].equals(CView.getServerlist().get(CView.getSelector().getSelectedIndex()))){ // if the server has the same network as selected
						String[] serverNameSplit = CView.getServers().get(i)[0].split("="); // split the name so sort will sort on name (not n123=)
						String ServerInfo = serverNameSplit[1]+":"+CView.getServers().get(i)[1]+":"+CView.getServers().get(i)[2]+":"+CView.getServers().get(i)[3]; // creates a string with full serverinfo
						list.add(ServerInfo);	// adds the server to the temp list
						CView.getServers().remove(i);	// removes it from the serverlist
					}
				}
				Collections.sort(list);	// sorts the list
				for(String sorted : list){	// loops trough the list
					String[] ServerInfoSplited = sorted.split(":");	//splits the string
					ServerInfoSplited[0] = "n"+CView.getServers().size()+"="+ServerInfoSplited[0]; // adds the n123= to the name so it will get the same as the other servers
					CView.getServers().add(ServerInfoSplited);	// adds the servers to the serverlist
				}
				CView.setServers(CView.getSelector().getSelectedIndex()); //refreshing the servers
				CView.getServer().updateUI(); // updates the combobox
			}
		});
	}
	
	
	/**
	 * This shows a dialog message where u can put in info about a server or edit the info
	 * @author Dybdal
	 * @since 1.3
	 * @version 1.4
	 */
	public String[] serverConfig(String navn, String irc, String prt, String gruppe){
		JLabel desc1 = new JLabel("Navn");
		JLabel server1 = new JLabel("IRC server");	// creates all the components for the dialog
		JLabel port1 = new JLabel("Port");
		JLabel group1 = new JLabel("Servergruppe");
		JTextField desc = new JTextField(navn);
		JTextField server = new JTextField(irc);
		JTextField port = new JTextField(prt);
		JTextField group = new JTextField(gruppe); // stores all the components to a array
		JComponent[] input = new JComponent[] { desc1, desc, server1, server, port1, port, group1, group };
		if(JOptionPane.showConfirmDialog(null, input, "Server", JOptionPane.OK_CANCEL_OPTION) == 0){		
			String[] ServerInfo = new String[] { "n"+CView.getServers().size()+"="+desc.getText()+"SERVER", server.getText(), port.getText()+"GROUP", group.getText() }; 
			return ServerInfo;	//shows the dialog and creates a array with the user inputs
		}
		return null;	// if the user cancels return null
	}
	
	
	/**
	 * Finds the selected server in the connection panel
	 * @author Dybdal
	 * @since 1.4
	 * @version 1.6
	 */
	public ArrayList<String> findSelectedServer()	{
		int i = 0;
		for(String[] data : CView.getServers()){	// loops trough the serverlist
			String[] ServerNameSplited = data[0].split("=");	// splits the name
			String ServerName = ServerNameSplited[1].substring(0, ServerNameSplited[1].length()-6); // cuts SERVER from name
			if(ServerName.equals(CView.getServer().getSelectedItem()) && data[3].equals(CView.getSelector().getSelectedItem())){ // if the name is the same as selected in the comboboxes
				ArrayList<String> server = new ArrayList<String>();
				server.add(data[0]);
				server.add(data[1]);	// creates an arraylist and adds the server info
				server.add(data[2]);
				server.add(data[3]);
				server.add(Integer.toString(i)); // adds the server index
				return server;
			}
			i++;
		}
		return null; 
	}
	
	
	/**
	 * shows the connection panel
	 * @author Dybdal
	 * @since 1.4
	 * @version 1.6
	 */
	public void showFrame(){
		frame.show();
	}

	/**
	 * sets the menucontroller
	 * @author Dybdal
	 * @since 1.4
	 * @version 1.6
	 */
	public void getMC(MenuController menuController) {
		menuC = menuController;
	}

	/**
	 * sets the toolbarcontroller
	 * @author Dybdal
	 * @since 1.4
	 * @version 1.6
	 */
	public void getTC(ToolbarController toolbarController) {
		toolbarC = toolbarController;
	}
	
	
	
	
}
